import React, { Component } from 'react'

export default class Todolist extends Component {
    state = {list: JSON.parse(localStorage.getItem("key")) || []}
    // inpChange = (type)=>{
    //     return (e)=>{
    //         this.setState( {[type]: e.target.value} )
    //     }
    // }
    addItem = (e)=>{
        if(e.keyCode==13){
            let val = e.target.value;

            //不建议,这是对原数组更改
            // this.state.list.unshift(val);
            // this.setState({list: this.state});

            //setstate是异步的
            this.setState( {list: [val, ...this.state.list]}, ()=>{
                //实现本地存储,只有放在回调函数里面才能拿到最新的状态
                localStorage.setItem("key", JSON.stringify(this.state.list));
            })
            e.target.value = '';
        }
    }
    delItem = (idx)=>{
        this.setState( {list: this.state.list.filter((_/*下划线站位*/,index)=>idx!=index)} , ()=>{
            localStorage.setItem("key", JSON.stringify(this.state.list));
        })

    }
    render() {
        const {inp,list} = this.state;
        return (
            <div>
                <input 
                    // value={inp}
                    // onChange={this.inpChange('inp')}
                    onKeyUp={this.addItem}
                />
                <h2>正在进行的条数: {list.length}</h2>
                <ul>
                    {
                        list.map( (item,index)=>(
                            <li>
                                <input type="checkbox" />
                                {item}  ---
                                <button onClick = {()=>this.delItem(index)} id = {item.value}>删除</button>
                            </li>
                        ))
                    }
                </ul>
            </div>
        )
    }
}
